<template>
  <div class="add">
    <a-modal v-model:visible="visible" :width="600" :title="type === 1 ? '积分增发' : '积分销毁'" @ok="onOk" @cancel="hideModel">
      <a-form :model="formState" :rules="rules" layout="horizontal" ref="formRef" name="add_form" labelAlign="left">
        <a-form-item label="数量" name="total">
          <a-input-number style="width: 100%" v-model:value="formState.total" :precision="0" :min="1" :max="999999999" :formatter="(value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')" :parser="(value) => value.replace(/\$\s?|(,*)/g, '')" />
        </a-form-item>

        <a-form-item label="说明简介" name="remark">
          <a-textarea :rows="4" v-model:value="formState.remark" allow-clear :maxlength="150" />
        </a-form-item>
        <a-form-item class="w-[70%]" name="files" label="文件" extra="">
          <a-upload v-model:file-list="fileList" name="file" list-type="picture-card" :maxCount="1" class="avatar-uploader" :action="uploadApi" :headers="{ authorization: token }" :before-upload="beforeUploadFile" @change="handleChange">
            <div>
              <loading-outlined v-if="variable.uploadLoading" :style="{ color: '#13c2c2' }" />
              <plus-outlined v-else :style="{ color: '#13c2c2' }" />
              <div class="ant-upload-text">上传文件</div>
            </div>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { message } from 'ant-design-vue'
  import { Rule } from 'ant-design-vue/lib/form'
  import { computed, reactive, ref, watch } from 'vue'

  import { requestDestroyPoints, requestMintPoints } from '/@/api/integral/integralIssuer'
  import { HttpCodeEnum } from '/@/enums/httpEnum'
  import { getToken } from '/@/storage'
  const token = getToken() || ''
  const uploadApi = `${import.meta.env.VITE_BASE_API_PATH}/contentFile/upload/V1`
  const props = defineProps({
    type: { type: Number, default: 1 },
    visible: { type: Boolean, default: false },
    data: { type: Object, default: () => {} },
  })
  const variable = reactive({
    confirmLoading: false,
    uploadLoading: false,
  })
  const emits = defineEmits(['update:visible', 'success'])
  const visible = computed({
    get: () => props.visible,
    set: (val: boolean) => emits('update:visible', val),
  })

  const formRef = ref()
  const formState: any = ref({
    total: '',
    remark: '',
    files: '',
  })
  const fileList: any = ref([])
  watch(
    () => visible.value,
    (newVal, oldVal) => {
      if (newVal && !oldVal) formRef.value?.resetFields()
    },
  )
  /** 自定义校验规则 */
  const rules: Record<string, Rule[]> = {
    total: [{ required: true, message: '请输入数量' }],
    remark: [
      { required: true, message: '请输入内容' },
      { max: 150, message: '最多不能超过150个字符' },
    ],
    files: [{ required: true, message: '请上传文件' }],
  }

  const beforeUploadFile = (file) => {
    const isJpgOrPng = ['.jpg', '.jpeg', '.png', '.rar', '.zip', '.doc', '.docx', '.pdf'].includes(file.name.substr(file.name.lastIndexOf('.')).toLowerCase())
    if (!isJpgOrPng) {
      message.error('支持格式：.jpg .jpeg .png .rar .zip .doc .docx .pdf')
    }
    const isLt2M = file.size / 1024 / 1024 < 50
    if (!isLt2M) {
      message.error('单个文件不能超过50M')
    }
    return isJpgOrPng && isLt2M
  }

  const handleChange = (info) => {
    if (info.file.status === 'uploading') {
      variable.uploadLoading = true
      return
    }
    if (info.file.status === 'done') {
      message.success('上传成功')
      formState.value.files = info.file.response.responseData
      variable.uploadLoading = false
    }
    if (info.file.status === 'error') {
      variable.uploadLoading = false
      message.error(info.file.response.responseMessage || '上传错误')
    }
  }
  /**
   * 确定
   */
  const onOk = () => {
    formRef.value
      .validate()
      .then(async () => {
        if (props.type === 1) {
          mintPoints()
        } else {
          destroyPoints()
        }
      })
      .catch((res) => {
        console.log('catch: ', res)
      })
  }

  const mintPoints = async () => {
    variable.confirmLoading = true
    const { responseCode } = await requestMintPoints({ ...formState.value, coinId: props.data.coinId }).finally(() => {
      variable.confirmLoading = false
    })

    if (responseCode === HttpCodeEnum.SUCCESS) {
      message.success('操作成功')
      hideModel()
      emits('success')
    }
  }

  const destroyPoints = async () => {
    variable.confirmLoading = true
    const { responseCode } = await requestDestroyPoints({ ...formState.value, coinId: props.data.coinId }).finally(() => {
      variable.confirmLoading = false
    })

    if (responseCode === HttpCodeEnum.SUCCESS) {
      hideModel()
      visible.value = false
      emits('success')
    }
  }
  const hideModel = () => {
    formState.value.total = ''
    formState.value.remark = ''
    formState.value.files = ''
    fileList.value = []
    visible.value = false
  }
</script>

<style lang="less" scoped>
  .logo {
    position: absolute;
    top: 0;
    cursor: pointer;
  }
</style>
